package cn.ljy.common.utils.requests;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * 当在web调用时，会自动生效。
 * 如果是使用junit测试非web业务，则会获取不到
 */
public class RequestUtil {
    /**
     * 获取Web应用的HttpServletRequest对象：request对象
     * @return null表示获取不到，即不是以web方式访问
     */
    private static HttpServletRequest getRequest() {
        if(RequestContextHolder.getRequestAttributes()!=null) {//如果是不通过web调用本aop（例如定时程序或是业务层调用，不会获得web对象）
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            return request;
        }else{
            return null;
        }
    }

    /**
     * 获取客户端的IP
     * @return
     */
    public static String getClientIp() {
        try {
            HttpServletRequest request=getRequest();
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null) {
                ip = request.getRemoteAddr();
            }
            if (ip != null && ip.length() > 50) {
                ip = ip.substring(0, 50);
            }
            return ip;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取项目根目录的网址
     * @return
     */
    public static String getBasePath(){
        String basePath="";
        HttpServletRequest request=getRequest();
        if(request!=null){
            basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";//获取项目根目录网址
        }

        return basePath;
    }
}
